package com.laobiao.paChong.wanyijunshi.sina.execut;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.annotation.NotThreadSafe;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.laobiao.paChong.wanyijunshi.sina.model.SinaContentModel;
import com.laobiao.paChong.wanyijunshi.util.FileUtils;

public class ExecuteSinaZw implements Runnable{
	private Elements newsUl;
	private String baseDir;
	public ExecuteSinaZw(Elements newsUl,String baseDir) {
		this.newsUl=newsUl;
		this.baseDir=baseDir;
	}

	@Override
	public void run() {
		
		for (Element element : newsUl) {
			FileWriter witer=null;
			try {
				SinaContentModel contentModel = new SinaContentModel(element);
				String typePath = String.join("/", contentModel.getClassify());
				String path=baseDir+"/"+(typePath!=null?typePath+"/":"")+FileUtils.convertFileName(contentModel.getTitle())+".txt";
				//System.out.println(path);
				File f=new File(path);
				if(!f.exists()){
					File pf = f.getParentFile();
					if(!pf.exists())
						pf.mkdirs();
					f.createNewFile();
//					BufferedWriter witer=new BufferedWriter();
					witer=new FileWriter(f);
					witer.write("【标题】:"+contentModel.getTitle()+"\r\n");
					witer.write("【主题】:"+String.join(" ", contentModel.getZtc())+"\r\n");
					witer.write("【编辑媒体】:"+contentModel.getEditMedia()+"\r\n");
					witer.write("【来源媒体】:"+contentModel.getSourceMedia()+"\r\n");
					witer.write("【生产日期】:"+contentModel.getNewsDate()+"\r\n");
					witer.write("【正文地址】:"+contentModel.getInforUri()+"\r\n");
					witer.write("【正文】:\r\n"+contentModel.getContent()+"\r\n");
					witer.flush();
					witer.close();
					//System.out.println("爬取数据："+contentModel.getTitle());
				}else{
					System.out.println("数据已存在:"+contentModel.getTitle());
				}
				
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
			}finally {
				if(witer!=null){
					try {
						witer.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			
		}
	}

}
